// 弹出的模态对话框

import Context from "./context";
import { useContext } from "react";
import { TextItem, ListItem } from "./item";
import { v4 as uuidv4 } from "uuid";
import { insert, getByValue } from "../action/orm";

// operator 是操作类型，增加或编辑
export default function Popup({
  handleSubmit,
  operator,
  showPopup,
  switchAlert,
}) {
  const { data, select, meta } = useContext(Context);

  // 通过 formData 获取数据，拼接为 json
  const getData = async (formData) => {
    let json_data = {};
    for (const [name, value] of formData) {
      const item = meta.form.find((item) => item.name === name);
      if (item.source) {
        const column = item.source.split(".")[1];
        const table = item.source.split(".")[0];
        const records = await getByValue(table, column, value);
        json_data[item.name] = {
          connect: {
            id: records[0].id,
          },
        };
        console.log("json_data inner", json_data);
      } else {
        json_data[name] = value;
      }
    }

    return json_data;
  };

  const submitEvent = async (formData) => {
    const json_data = await getData(formData);

    // 插入数据
    const result = await insert(meta.table, json_data);

    // 显示提示信息
    switchAlert(result.message, true);

    // 关闭弹出对话框
    showPopup(false);
  };

  return (
    <div className="mx-auto w-full max-w-xl">
      <form
        className="card mb-4 rounded bg-white px-8 pb-8 pt-6 shadow-md"
        action={submitEvent}
        id="router_form"
      >
        <span className="card-title mb-10 mt-2 gap-2">
          {`${operator === "add" ? "增加" : "编辑"}${meta.name}`}
        </span>
        <div className="grid grid-cols-6 gap-2">
          <div className="col-span-2">
            {meta.form[0].type === "list" ? (
              <ListItem
                label={meta.form[0].label}
                list={meta.form[0].data}
                formName={meta.form[0].name}
              />
            ) : (
              <TextItem item={meta.form[0]} formName={meta.form[0].name} />
            )}
          </div>
          <div className="col-span-4 mb-4">
            <TextItem item={meta.form[1]} formName={meta.form[1].name} />
          </div>
        </div>
        {meta.form.slice(2).map((item, index) => (
          <div key={uuidv4()} className="mb-4">
            <div key={index + 100}>
              <TextItem item={item} formName={item.name} />
            </div>
          </div>
        ))}
        <div className="flex items-center justify-end gap-2">
          <button
            className="btn btn-wide"
            type="button"
            onClick={() => showPopup(false)}
          >
            取消
          </button>

          <button className="btn btn-neutral btn-wide" type="submit">
            提交
          </button>
        </div>
      </form>
    </div>
  );
}
